/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
@file:JvmName("LogAnonymizer")
package com.android.tools.log

import com.android.SdkConstants
import com.google.common.hash.Hashing
import java.nio.charset.StandardCharsets
import java.security.SecureRandom

/** Utility methods used to anonymize information going to the local logs. */
private val SALT = Integer.toString(SecureRandom().nextInt())

/**
 * Returns whether a given class name belong to a namespace that does not need to be anonymized
 */
fun isPublicClass(className: String?): Boolean {
  var className = className ?: return false
  className = className.replace("/", ".")
  return className.startsWith("java.") || className.startsWith("javax.") ||
         className.startsWith(SdkConstants.ANDROID_SUPPORT_ARTIFACT_PREFIX) ||
         className.startsWith(SdkConstants.ANDROID_PKG_PREFIX) ||
         className.startsWith("com.google.")
}

/**
 * Returns a hash for the given class name. The hash value will be consistent only for the current session. Once the IDE is shutdown,
 * the hash for the class name will change.
 */
fun anonymizeClassName(className: String?): String {
  var className = className ?: return "null"
  className = className.replace("/", ".")
  return if (isPublicClass(className)) className
  else "class:" + Hashing.sha256().hashString(SALT + className, StandardCharsets.UTF_8).toString()
}